package net.suncaper.psychological.web.controller;

import net.suncaper.psychological.common.framework.simplemvc.RequestMapping;
import net.suncaper.psychological.common.utils.Result;
import net.suncaper.psychological.model.domain.VisitRecord;
import net.suncaper.psychological.service.IVisitRecordService;
import net.suncaper.psychological.service.impl.VisitRecordServiceImpl;
import com.alibaba.fastjson.JSON;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

@RequestMapping("/api/visit-record")
public class VisitRecordController {
    private final IVisitRecordService visitRecordService = new VisitRecordServiceImpl();

    @RequestMapping("/initial")
    public void getInitialVisitRecords(HttpServletRequest request, HttpServletResponse response) {
        try {
            System.out.println("开始查询初访记录");
            List<VisitRecord> visitRecords = visitRecordService.getInitialVisitRecords();
            System.out.println("初访记录数量: " + visitRecords.size());
            for (VisitRecord r : visitRecords) {
                System.out.println("DEBUG_CONTROLLER: id=" + r.getId() + ", visit_time=" + r.getVisit_time());
            }
            Result.success(visitRecords, "查询初访记录成功").writeTo(response);
        } catch (Exception e) {
            System.out.println("查询初访记录异常: " + e.getMessage());
            e.printStackTrace();
            Result.error("查询初访记录异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/create")
    public void createVisitRecord(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            System.out.println("收到创建初访记录请求数据: " + jsonData);
            
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            
            VisitRecord visitRecord = new VisitRecord();
            visitRecord.setAppointment_id(Long.valueOf(data.get("appointment_id").toString()));
            visitRecord.setVisitor_id(Long.valueOf(data.get("visitor_id").toString()));
            visitRecord.setType((String) data.get("type"));
            String visitTimeStr = (String) data.get("visit_time");
            Timestamp visitTime = null;
            if (visitTimeStr != null && !visitTimeStr.isEmpty()) {
                visitTimeStr = visitTimeStr.replace('T', ' ');
                if (visitTimeStr.length() == 16) {
                    visitTimeStr += ":00";
                }
                visitTime = Timestamp.valueOf(visitTimeStr);
            }
            visitRecord.setVisit_time(visitTime);
            visitRecord.setRisk_level((String) data.get("risk_level"));
            visitRecord.setProblem_type((String) data.get("problem_type"));
            visitRecord.setConclusion((String) data.get("conclusion"));
            visitRecord.setNote((String) data.get("note"));
            
            boolean success = visitRecordService.addVisitRecord(visitRecord);
            
            if (success) {
                Result.success(true, "初访记录创建成功").writeTo(response);
            } else {
                Result.error("初访记录创建失败").writeTo(response);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("创建初访记录异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/approve")
    public void approveVisitRecord(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            Long id = Long.valueOf(data.get("id").toString());
            
            // 获取初访记录，根据结论决定后续处理
            VisitRecord visitRecord = visitRecordService.getVisitRecordById(id);
            if (visitRecord == null) {
                Result.error("未找到初访记录").writeTo(response);
                return;
            }
            
            String conclusion = visitRecord.getConclusion();
            String newType;
            String message;
            
            if ("无需咨询".equals(conclusion)) {
                // 如果结论是无需咨询，标记为已完成，不进入咨询安排
                newType = "COMPLETED";
                message = "审核通过，该学生无需咨询，流程已完成";
                System.out.println("初访结论为无需咨询，设置类型为COMPLETED");
            } else {
                // 如果结论是建议心理咨询，进入咨询安排
                newType = "CONSULT";
                message = "审核通过，已进入咨询安排队列";
                System.out.println("初访结论为建议心理咨询，设置类型为CONSULT");
            }
            
            boolean success = visitRecordService.updateVisitRecordType(id, newType);
            Result.success(success, message).writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("审核通过异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/reject")
    public void rejectVisitRecord(HttpServletRequest request, HttpServletResponse response) {
        try {
            String jsonData = getRequestBody(request);
            Map<String, Object> data = JSON.parseObject(jsonData, Map.class);
            Long id = Long.valueOf(data.get("id").toString());
            Long appointmentId = Long.valueOf(data.get("appointment_id").toString());
            boolean success = visitRecordService.rejectVisitRecord(id, appointmentId);
            Result.success(success, "已打回").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("打回异常: " + e.getMessage()).writeTo(response);
        }
    }

    @RequestMapping("/consult")
    public void getConsultVisitRecords(HttpServletRequest request, HttpServletResponse response) {
        try {
            List<Map<String, Object>> visitRecords = visitRecordService.getConsultVisitRecordsWithAppointment();
            Result.success(visitRecords, "查询咨询安排记录成功").writeTo(response);
        } catch (Exception e) {
            e.printStackTrace();
            Result.error("查询咨询安排记录异常: " + e.getMessage()).writeTo(response);
        }
    }

    private String getRequestBody(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        try (BufferedReader reader = request.getReader()) {
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        }
        return sb.toString();
    }
} 